package com.jwt.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.jwt.server.filter.JwtAuthenticationFilter;
import com.jwt.server.filter.JwtLoginFilter;
import com.jwt.server.filter.JwtLoginFilter2;
import com.jwt.server.provider.CustomAuthenticationProvider;

/**
 * 通过SpringSecurity的配置，将JWTLoginFilter，JWTAuthenticationFilter组合在一起
 * 
 * @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 在springboot1.5.8的时候该注解是可以用的
 *                                                  具体看源码
 * @author zyl
 *
 */
@Configuration
@Order(55)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Qualifier("userDetailServiceImpl")
	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;

	@Override
	public void configure(WebSecurity web) throws Exception {
		super.configure(web);
	}
 
	@Override
	protected void configure(HttpSecurity http) throws Exception {

		// 自定义 默认
		http.cors().and().csrf().disable().authorizeRequests().antMatchers("/users/signup").permitAll().anyRequest()
				.authenticated()
//				.and().addFilter(new JwtLoginFilter(authenticationManager()))// 默认登录过滤器
				.and()
//				.addFilter(new JwtLoginFilter(authenticationManager()))// 登录授权生成token
//				.addFilterAfter(new JwtLoginFilter2(authenticationManager()), JwtLoginFilter.class)
				.addFilter(new JwtLoginFilter2(authenticationManager()))// 登录授权生成token
				.addFilter(new JwtAuthenticationFilter(authenticationManager()));//认证授权类

	}
	
	// 该方法是登录的时候会进入
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
//    	auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
        // 使用自定义身份验证组件
        auth.authenticationProvider(new CustomAuthenticationProvider(userDetailsService, bCryptPasswordEncoder));
    }

}
